package com.keiou.drink.api.converter;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.keiou.drink.api.AbsSubscriber;
import com.keiou.drink.api.exception.ApiException;
import com.keiou.drink.response.base.HttpResult;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by Bob on 2017/1/20
 */
public class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    CustomGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        try {
            HttpResult result = gson.fromJson(response, HttpResult.class);
            if (result.isSuccess()) {
                return adapter.fromJson(response);
            } else {
                throw new ApiException(result.getCode(), result.getMsg());
            }
        } catch (JsonSyntaxException io) {
            throw new ApiException(AbsSubscriber.PARSE_ERROR, "数据解析失败");
        } finally {
            value.close();
        }
    }
}
